// pages/my-coupon/index.js
import config from '../../etc/config'

const {
  $Toast
} = require('../../components/dist/base/index');

var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status: 0,
    coupons: [],
    current: '1',
    orderId:'',
    currentPage: 1
  },
  handleChange({detail}) {
    this.setData({
      status: detail.key
    });
    this.getCouponsList();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.hideShareMenu()
    if(options.orderId){
      this.setData({ orderId: options.orderId})
      this.getCouponsToPay(options.orderId)
    }else{
      this.getCouponsList()
    }
  },
  getCouponsList() {
    wx.showLoading({
      title: '加载中'
    });
    let params = {
      userId: wx.getStorageSync('userId'),
      current: this.data.current,
      status: this.data.status,
      limit: 10
    }
    let token = wx.getStorageSync('token')
    config._post('/coupon/couponListForUser', token, params).then(res => {
      wx.hideLoading()
      if (res.data) {
        this.setData({
          coupons: res.data.records,
          currentPage: res.data.currPage + 1
        })
        wx.stopPullDownRefresh()
      }
    })
  },
  gitCoupon(e){
    if(this.data.orderId){
      var pages = getCurrentPages(); // 获取页面栈
      var prevPage = pages[pages.length - 2]; // 上一个页面
      prevPage.setData({
        coupon: e.currentTarget.dataset.item
      })
      wx.navigateBack()
    }
  },
  getCouponsToPay(orderId){
    let params = {
      orderId: orderId
    }
    let token = wx.getStorageSync('token')
    config._post('/coupon/getCouponsToPay', token, params).then(res => {
      if (res.data) {
        this.setData({
          coupons: res.data
        })
      }
    })
  },
  onShow(){
    if (this.data.orderId) {
      this.getCouponsToPay(this.data.orderId)
    } else {
      this.getCouponsList()
    }
  },
  onPullDownRefresh: function () {
    this.setData({
      currentPage: 1
    })
    if (this.data.orderId) {
      this.getCouponsToPay(this.data.orderId)
    } else {
      this.getCouponsList()
    }
  },
  goCouponsCenter(){
    wx.navigateTo({
      url: '../coupon-center/index',
    })
  }
})